package com.ruoyi.web.controller.app.im.app.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.exception.base.XException;
import com.ruoyi.framework.web.exception.base.XResult;
import com.ruoyi.im.domain.*;
import com.ruoyi.im.mapper.*;
import com.ruoyi.sj.domain.WqEweiShopMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

import com.ruoyi.sj.domain.Order;
import com.ruoyi.sj.mapper.OrderMapper;
import com.ruoyi.util.SerialNumber;
import com.ruoyi.web.controller.pay.PayComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AppUserService {

    @Autowired(required = false)
    private UserMapper userMapper;//用户mapper

    @Autowired(required = false)
    private FriendApplicationMapper friendApplicationMapper;//好友申请mapper

    @Autowired(required = false)
    private FriendsMapper friendsMapper;//好友表mapper

    @Autowired(required = false)
    private GroupingMapper groupingMapper;//用户分组mapper

    @Autowired(required = false)
    private UserGroupMapper userGroupMapper;//用户群mapper

    @Autowired(required = false)
    private GroupNicknameMapper groupNicknameMapper;//群昵称mapper

    @Autowired(required = false)
    private GroupDetailMapper groupDetailMapper;//群明细mapper

    @Autowired(required = false)
    private GroupGroupingDetailsMapper groupGroupingDetailsMapper;//用户群分组mapper

    @Autowired(required = false)
    private BlacklistMapper blacklistMapper;//黑名单

    @Autowired(required = false)
    private AnExcuseMapper anExcuseMapper;//禁言mapper

    @Autowired
    private PayComponent payComponent;

    private SerialNumber serial = new SerialNumber("CO");

    /**
     * 根据用户id查询用户分组信息
     *
     * @param userId
     * @return
     */
    public List<UserGroupList> findUserGroupList(String userId) {
        return userMapper.findUserGroupList(userId);
    }

    /**
     * 搜索好友
     *
     * @param search
     * @return
     */
    public List<User> findUserByNickNameList(String search) {
        return userMapper.findUserByNickNameList(search);
    }

    /**
     * 发送好友申请
     *
     * @param map
     * @return
     */
    public int sendingFriendsApplication(Map<String, Object> map) {
        FriendApplication friendApplication1 = friendApplicationMapper.findFriendApplicationByApplicantIdAndClaimantId(map.get("claimantId") + "", map.get("applicantId") + "");
        if (friendApplication1 != null) {
            if (friendApplication1.getStatus() == 1) {
                throw new XException("你们已经是好友了");
            } else {
                friendApplication1.setValidationMessage(map.get("validationMessage") + "");//验证信息
                friendApplication1.setRemarks(map.get("remarks") + "");//备注
                friendApplication1.setGroupId(Long.valueOf(map.get("groupId") + ""));//分组id
                friendApplication1.setAddTime((System.currentTimeMillis() / 1000) + "");
                friendApplication1.setStatus(0);
                return friendApplicationMapper.updateFriendApplication(friendApplication1);
            }
        } else {
            FriendApplication friendApplication = new FriendApplication();
            friendApplication.setValidationMessage(map.get("validationMessage") + "");//验证信息
            friendApplication.setApplicantId(Long.valueOf(map.get("applicantId") + ""));//申请人
            friendApplication.setRemarks(map.get("remarks") + "");//备注
            friendApplication.setGroupId(Long.valueOf(map.get("groupId") + ""));//分组id
            friendApplication.setClaimantId(Long.valueOf(map.get("claimantId") + ""));//被申请人
            friendApplication.setApplyType(1);
            friendApplication.setStatus(0);
            friendApplication.setAddTime((System.currentTimeMillis() / 1000) + "");
            return friendApplicationMapper.insertFriendApplication(friendApplication);
        }
    }

    /**
     * 好友申请确认
     *
     * @param map
     * @return
     */
    public int friendsConfirmation(Map<String, Object> map) {
        int count = 0;
        if (StringUtils.isBlank(map.get("friendId") + "")) {
            throw new XException("数据id不能为空");
        }
        FriendApplication friendApplication = friendApplicationMapper.selectFriendApplicationById(Long.valueOf(map.get("friendId") + ""));
        if (friendApplication != null) {
            Friends friends2 = friendsMapper.findFriendsByfriendsUserId(friendApplication.getApplicantId() + "", friendApplication.getClaimantId() + "", null);
            Blacklist blacklist = blacklistMapper.findBlacklistByUserIdAndpullerUserId(friendApplication.getClaimantId() + "", friendApplication.getApplicantId() + "");
            if (blacklist != null) {
                blacklistMapper.deleteBlacklistById(blacklist.getId());
            }
            if (friends2 != null) {
                friendsMapper.deleteFriendsById(friends2.getId());
            }
            List<Friends> friendsList = Lists.newArrayList();
            Friends friends = new Friends();//好友实体类
            friends.setUserId(friendApplication.getClaimantId());//用户id
            friends.setFriendsUserId(friendApplication.getApplicantId());//好友id
            friends.setGroupingId(5L);//分组id
            friends.setAddTime(DateUtils.getTime());//添加时间
            friendsList.add(friends);
            friends = new Friends();//好友实体类
            friends.setUserId(friendApplication.getApplicantId());//用户id
            friends.setFriendsUserId(friendApplication.getClaimantId());//好友id
            friends.setGroupingId(friendApplication.getGroupId());//分组id
            friends.setAddTime(DateUtils.getTime());//添加时间
            friendsList.add(friends);
            for (Friends friends1 : friendsList) {
                count = friendsMapper.insertFriends(friends1);
            }
            if (count > 0) {
                friendApplication.setStatus(Integer.valueOf(map.get("type") + ""));
                friendApplicationMapper.updateFriendApplication(friendApplication);
            }
        }
        return count;
    }

    /**
     * 发送群申请
     *
     * @param map
     * @return
     */
    public Object findUserGroupListByUserId(Map<String, Object> map) {
        UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.parseLong(String.valueOf(map.get("groupsId"))));
        if (userGroup != null) {
            int allowNum = userGroupMapper.queryLimit(userGroup.getId());
            if (allowNum > 0) {
                String cost = userGroup.getCost();
                FriendApplication friendApplication = friendApplicationMapper.findFriendApplicationByApplicantIdAndGruopsId(map.get("applicantId") + "", map.get("groupsId") + "");
                if (friendApplication != null) {
                    if (friendApplication.getStatus() == 1) {
                        throw new XException("你已经是该群成员，无需在进行添加");
                    } else {
                        friendApplication.setValidationMessage(map.get("validationMessage") + "");//验证信息
                        friendApplication.setApplicantId(Long.valueOf(map.get("applicantId") + ""));//申请人
                        friendApplication.setRemarks(map.get("remarks") + "");//备注
                        friendApplication.setGroupsId(Long.valueOf(map.get("groupsId") + ""));
                        friendApplication.setApplyType(2);
                        friendApplication.setStatus(0);
                        friendApplication.setAddTime((System.currentTimeMillis() / 1000) + "");
                        int count = friendApplicationMapper.updateFriendApplication(friendApplication);
                        if (count < 1) throw new XException("发送失败");
                    }
                } else {
                    friendApplication = new FriendApplication();
                    friendApplication.setValidationMessage(map.get("validationMessage") + "");//验证信息
                    friendApplication.setApplicantId(Long.valueOf(map.get("applicantId") + ""));//申请人
                    friendApplication.setRemarks(map.get("remarks") + "");//备注
                    friendApplication.setGroupsId(Long.valueOf(map.get("groupsId") + ""));
                    friendApplication.setApplyType(2);
                    friendApplication.setStatus(0);
                    friendApplication.setAddTime((System.currentTimeMillis() / 1000) + "");
                    int count = friendApplicationMapper.insertFriendApplication(friendApplication);
                    if (count < 1) throw new XException("发送失败");
                }
                if (StringUtils.isNotBlank(cost) && !StringUtils.equals(cost, "0")) {
                    // 付费群
                    Object PT = map.get("payType");
                    if (PT != null) {
                        String payType = String.valueOf(PT);
                        if (payType.matches("^balance|weChatPay|aliPay|weChatPayApp|weChatPayApplet$")) {
                            Order order = new Order();
                            order.setSn(serial.getAtomicNumber());
                            order.setType(5);
                            order.setPayType(payType);
                            order.setMemberId(String.valueOf(friendApplication.getApplicantId()));
                            order.setCreateDate(new Date());
                            order.setPayMoney(cost);
                            order.setGoodsId(String.valueOf(friendApplication.getId()));
                            order.setPayPassword(String.valueOf(map.get("payPassword")));
                            payComponent.sendToPay(order);
                            if ("balance".equals(payType)) {
                                payComponent.hanldeSuccess(order);
                            }
                            return order;
                        } else {
                            throw new XException("请提交指定付款方式");
                        }
                    } else {
                        throw new XException("请选择支付类型");
                    }
                }
            } else {
                throw new XException("您申请的群已达上限");
            }
        } else {
            throw new XException("您申请的群已经解散");
        }
        return null;
    }

    /**
     * 群确认
     *
     * @param map
     * @return
     */
    public int groupConfirmation(Map<String, Object> map) {
        FriendApplication friendApplication = friendApplicationMapper.selectFriendApplicationById(Long.valueOf(map.get("friendId") + ""));
        if (Integer.valueOf(map.get("type") + "") == 1) {
            GroupGroupingDetails groupGroupingDetails = new GroupGroupingDetails();
            groupGroupingDetails.setGroupId(Long.valueOf(map.get("groupsId") + ""));
            groupGroupingDetails.setGroupingId(Long.valueOf(7));
            groupGroupingDetails.setUserId(Long.valueOf(map.get("applicantId") + ""));
            groupGroupingDetailsMapper.insertGroupGroupingDetails(groupGroupingDetails);
            GroupDetail groupDetail = new GroupDetail();
            groupDetail.setUserId(Long.valueOf(map.get("applicantId") + ""));
            groupDetail.setGroupId(Long.valueOf(map.get("groupsId") + ""));
            groupDetail.setAddTime(DateUtils.getTime());//添加时间
            groupDetailMapper.insertGroupDetail(groupDetail);
            GroupNickname groupNickname = new GroupNickname();
            groupNickname.setGroupId(Long.valueOf(map.get("groupsId") + ""));
            groupNickname.setUserId(Long.valueOf(map.get("applicantId") + ""));
            User user = userMapper.selectUserById(Long.valueOf(map.get("applicantId") + ""));
            if (user != null) {
                groupNickname.setNickname(user.getNickname());
            }
            groupNickname.setDisturb(2);
            groupNicknameMapper.insertGroupNickname(groupNickname);
            return 1;
        }
        if (friendApplication != null) {
            friendApplication.setStatus(Integer.valueOf(map.get("type") + ""));
            friendApplicationMapper.updateFriendApplication(friendApplication);
        }
        return 0;
    }


    /**
     * 查询用户被申请加为好友申请列表
     *
     * @param claimantId
     * @return
     */
    public List<FriendApplication> findFriendApplicationListByclaimantId(String claimantId, String type) {
        return friendApplicationMapper.findFriendApplicationListByclaimantId(claimantId, type);
    }


    /**
     * 查询自己的分组列表信息
     *
     * @param userId
     * @return
     */
    public List<Grouping> findGroupingListByUserId(String userId) {
        return groupingMapper.findGroupingListByUserId(userId);
    }

    /**
     * 根据id删除分组信息
     *
     * @param id
     * @return
     */
    public int deleteGroupingById(String id) {
        int count = 0;
        List<Friends> friendsList = friendsMapper.findFriendsByGroupingId(id);
        List<GroupGroupingDetails> groupGroupingDetailsList = groupGroupingDetailsMapper.findGroupingObgByGroupingId(id);
        if ((friendsList != null && friendsList.size() > 0) || (groupGroupingDetailsList != null && groupGroupingDetailsList.size() > 0)) {
            throw new XException("该分组下有分组成员，暂时不能进行删除");
        } else {
            return groupingMapper.deleteGroupingById(Long.valueOf(id));
        }
    }

    /**
     * 用户新增分组
     *
     * @param map
     * @return
     */
    public int createGrouping(Map<String, String> map) {
        int count = groupingMapper.findGroupingByName(map.get("name"), map.get("userId"));
        if (count > 0) {
            throw new XException("分组名称重复");
        }
        Grouping grouping = new Grouping();
        grouping.setName(map.get("name"));
        grouping.setUserId(Long.valueOf(map.get("userId")));
        grouping.setType(Integer.valueOf(map.get("type")));
        grouping.setAddTime(DateUtils.getTime());
        return groupingMapper.insertGrouping(grouping);
    }


    /**
     * 根据用户id查询用户分组信息
     *
     * @param userId
     * @return
     */
    public List<UserGroupGrouping> findUserGroupGroupingList(String userId) {
        return userMapper.findUserGroupGroupingList(userId);
    }

    /**
     * 查询群详情
     *
     * @param groupId
     * @return
     */
    public UserGroup findUserGroupListBygroupId(String groupId, String userId) {
        if (StringUtils.isBlank(userId)) {
            throw new XException(("用户id不能为空"));
        } else if (StringUtils.isBlank(groupId)) {
            throw new XException(("groupId不能为空"));
        }
        UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.valueOf(groupId));
        List<User> userList = userMapper.findUserGroupListBygroupId(groupId);
        userGroup.setUserList(userList);
        GroupGroupingDetails groupGroupingDetails = groupGroupingDetailsMapper.selectGroupGroupingDetailsByGroupIdAndUserId(userId, groupId);
        if (groupGroupingDetails != null) {
            Grouping grouping = groupingMapper.selectGroupingById(groupGroupingDetails.getGroupingId());
            if (grouping != null) {
                userGroup.setGroupingName(grouping.getName());
            }
        }
        GroupNickname groupNickname = groupNicknameMapper.selectGroupNicknameByGroupIdAndUserId(groupId, userId);
        if (groupNickname != null) {
            userGroup.setDisturb(groupNickname.getDisturb());
            userGroup.setGroupNickName(groupNickname.getNickname());
        }
        return userGroup;
    }


    /**
     * 查询群好友详情
     *
     * @param userId
     * @param groupId
     * @return
     */
    public User findUserByUserId(String userId, String groupId) {
        return userMapper.findUserByUserId(userId, groupId);
    }

    /**
     * 修改群设置
     *
     * @return
     */
    public int updateUserGroupSetting(Map<String, Object> map) {
        UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.valueOf(map.get("groupId") + ""));
        userGroup.setGroupSetting(Integer.valueOf(map.get("type") + ""));
        return userGroupMapper.updateUserGroup(userGroup);
    }


    /**
     * 设置群昵称
     *
     * @param map
     * @return
     */
    public int setGroupNickName(Map<String, String> map) {
        GroupNickname groupNickname = new GroupNickname();
        groupNickname = groupNicknameMapper.selectGroupNicknameByGroupIdAndUserId(map.get("groupId"), map.get("userId"));
        if (groupNickname != null) {
            groupNickname.setNickname(map.get("nickname"));//昵称
            return groupNicknameMapper.updateGroupNickname(groupNickname);
        } else {
            groupNickname = new GroupNickname();
            groupNickname.setUserId(Long.valueOf(map.get("userId")));//用户id
            groupNickname.setGroupId(Long.valueOf(map.get("groupId")));//所属群
            groupNickname.setNickname(map.get("nickname"));//昵称
            return groupNicknameMapper.insertGroupNickname(groupNickname);
        }
    }


    /**
     * 用户群分组设置
     *
     * @param map
     * @return
     */
    public int setGroupGrouping(Map<String, String> map) {
        GroupGroupingDetails groupGroupingDetails = new GroupGroupingDetails();
        groupGroupingDetails.setGroupId(Long.valueOf(map.get("groupId")));
        groupGroupingDetails.setGroupingId(Long.valueOf(map.get("groupingId")));
        groupGroupingDetails.setUserId(Long.valueOf(map.get("userId")));
        return groupGroupingDetailsMapper.insertGroupGroupingDetails(groupGroupingDetails);
    }

    /**
     * 把好友拉入黑名单
     *
     * @param map
     * @return
     */
    public int createBlacklist(Map<String, String> map) {
        if (StringUtils.isBlank(map.get("pullerUserId")) || StringUtils.isBlank(map.get("userId"))) {
            throw new XException("参数pullerUserId或者userId不能为空");
        }
        Friends friends = friendsMapper.findFriendsByfriendsUserId(map.get("userId"), map.get("pullerUserId"), "6");
        if (friends != null) {
            friendsMapper.deleteFriendsById(Long.valueOf(friends.getId()));
        }
        Friends friends1 = friendsMapper.findFriendsByfriendsUserId(map.get("pullerUserId"), map.get("userId"), "6");
        if (friends1 != null) {
            friends1.setGroupingId(6L);
            friendsMapper.updateFriends(friends1);
        }

        FriendApplication friendApplication = friendApplicationMapper.findFriendApplicationByApplicantIdAndClaimantId(map.get("userId") + "", map.get("pullerUserId") + "");
        if (friendApplication != null) {
            friendApplication.setStatus(9);
            friendApplicationMapper.updateFriendApplication(friendApplication);
        }
        FriendApplication friendApplication1 = friendApplicationMapper.findFriendApplicationByApplicantIdAndClaimantId(map.get("pullerUserId") + "", map.get("userId") + "");
        if (friendApplication1 != null) {
            friendApplication1.setStatus(9);
            friendApplicationMapper.updateFriendApplication(friendApplication1);
        }
//        friendsMapper.deleteFriendsByIds(new String[]{friends.getId()+"",friends1.getId()+""});
        Blacklist blacklist = new Blacklist();
        blacklist.setGroupId(6L);
        blacklist.setPullerUserId(Long.valueOf(map.get("pullerUserId")));
        blacklist.setUserId(Long.valueOf(map.get("userId")));
        return blacklistMapper.insertBlacklist(blacklist);
    }

    /**
     * 禁言群内用户
     *
     * @param map
     * @return
     */
    public int createAnExcuse(Map<String, String> map) {
        AnExcuse anExcuse = new AnExcuse();
        anExcuse.setGroupId(Long.valueOf(map.get("groupId")));
        anExcuse.setUserId(Long.valueOf(map.get("userId")));
        anExcuse.setExcuseTimeLen(Integer.valueOf(map.get("excuseTimeLen")));//禁言时长
        anExcuse.setRelieveTime(DateUtils.addDateMinut(Integer.valueOf(map.get("excuseTimeLen"))) / 1000);//解除禁言时间
        return anExcuseMapper.insertAnExcuse(anExcuse);
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param userId
     * @return
     */
    public Object findUserById(String userId) {
        String str[] = userId.split(",");
        return userMapper.selectUsersByIds(str);
    }

    /**
     * 用户好友设置备注名
     *
     * @param map
     * @return
     */
    public int updateFriendsMemoName(Map<String, String> map) {
        if (StringUtils.isBlank(map.get("pullerUserId")) || StringUtils.isBlank(map.get("userId"))) {
            throw new XException("参数pullerUserId或者userId不能为空");
        }
        Friends friends = friendsMapper.findFriendsByfriendsUserId(map.get("pullerUserId"), map.get("userId"), "6");
        if (friends != null) {
            friends.setMemoName(map.get("memoName"));
            return friendsMapper.updateFriends(friends);
        }
        return 0;
    }


    /**
     * 搜索群
     *
     * @param groupName
     * @return
     */
    public List<UserGroup> findUserGroupListByLickName(String type, String groupName, String longitude, String latitude) {
        return userGroupMapper.findUserGroupListByLickName(type, groupName, longitude, latitude);
    }

    /**
     * 根据用户id查询自己拉入黑名单好友数据
     *
     * @param map
     * @return
     */
    public List<Blacklist> selectBlacklistListByUserId(Map<String, String> map) {
        List<Blacklist> blacklistList = blacklistMapper.selectBlacklistListByUserId(map.get("userId"));
        return blacklistList;
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    public int deleteBlacklistUser(String id) {
        Blacklist blacklist = blacklistMapper.selectBlacklistById(Long.valueOf(id));
        if (blacklist != null) {
            Friends friends1 = friendsMapper.findFriendsByfriendsUserId(blacklist.getPullerUserId() + "", blacklist.getUserId() + "", null);
            if (friends1 != null) {
                friendsMapper.deleteFriendsById(friends1.getId());
            }
        }
        return blacklistMapper.deleteBlacklistById(Long.valueOf(id));
    }


    /**
     * 根据用户id及群id查询查询用户群分组信息进行分组的更新
     *
     * @param map
     * @return
     */
    public int selectGroupGroupingDetailsByGroupIdAndUserId(Map<String, String> map) {
        GroupGroupingDetails groupGroupingDetails = groupGroupingDetailsMapper.selectGroupGroupingDetailsByGroupIdAndUserId(map.get("userId"), map.get("groupId"));
        if (groupGroupingDetails != null) {
            groupGroupingDetails.setGroupingId(Long.valueOf(map.get("groupingId")));
        }
        return groupGroupingDetailsMapper.updateGroupGroupingDetails(groupGroupingDetails);
    }


    /**
     * 用户退群（踢出用户）
     *
     * @param map
     * @return
     */
    public int userRetreatGroup(Map<String, String> map) {
        int count = 0;
        if (StringUtils.isBlank(map.get("groupId"))) {
            throw new XException("群id不能为空");
        }
        if (StringUtils.isBlank(map.get("userId"))) {
            throw new XException("用户id不能为空");
        }
        GroupDetail groupDetail = groupDetailMapper.selectGroupDetailByGroupIdAndUserId(map.get("userId"), map.get("groupId"));
        GroupGroupingDetails groupGroupingDetails = groupGroupingDetailsMapper.selectGroupGroupingDetailsByGroupIdAndUserId(map.get("userId"), map.get("groupId"));
        if (groupDetail != null && groupGroupingDetails != null) {
            groupDetailMapper.deleteGroupDetailById(groupDetail.getId());
            groupGroupingDetailsMapper.deleteGroupGroupingDetailsById(groupGroupingDetails.getId());
            return 1;
        }
        return 0;
    }

    /**
     * 用户解散群
     *
     * @param map
     * @return
     */
    public int disbandedGroup(Map<String, String> map) {
        UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.valueOf(map.get("groupId")));
        int count = 0;
        if (userGroup != null) {
            GroupDetail groupDetail = new GroupDetail();
            groupDetail.setGroupId(userGroup.getId());
            List<GroupDetail> groupDetailList = groupDetailMapper.selectGroupDetailList(groupDetail);
            GroupGroupingDetails groupGroupingDetails = new GroupGroupingDetails();
            groupGroupingDetails.setGroupId(userGroup.getId());
            List<GroupGroupingDetails> groupGroupingDetailsList = groupGroupingDetailsMapper.selectGroupGroupingDetailsList(groupGroupingDetails);
            if (groupDetailList != null && groupDetailList.size() > 0) {
                for (GroupDetail detail : groupDetailList) {
                    groupDetailMapper.deleteGroupDetailById(groupDetail.getId());
                }
                count = 1;
            }
            if (groupGroupingDetailsList != null && groupGroupingDetailsList.size() > 0) {
                for (GroupGroupingDetails groupingDetails : groupGroupingDetailsList) {
                    groupGroupingDetailsMapper.deleteGroupGroupingDetailsById(groupingDetails.getId());
                }
                count = 1;
            }
            return count;
        }
        return 0;
    }


    /**
     * 群主修改群名称
     *
     * @param map
     * @return
     */
    public int updateUserGroup(Map<String, String> map) {
        UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.valueOf(map.get("groupId")));
        if (userGroup != null) {
            userGroup.setGroupName(map.get("groupName"));
        }
        return userGroupMapper.updateUserGroup(userGroup);
    }

    /**
     * 修改群消息勿扰状态
     *
     * @param map
     * @return
     */
    public int updateGroupDisturb(Map<String, String> map) {
        GroupNickname groupNickname = groupNicknameMapper.selectGroupNicknameByGroupIdAndUserId(map.get("groupId"), map.get("userId"));
        if (groupNickname != null) {
            groupNickname.setDisturb(Integer.valueOf(map.get("disturb")));
            return groupNicknameMapper.updateGroupNickname(groupNickname);
        }
        return 0;
    }

    /**
     * 用户修改分组名称
     *
     * @param map
     * @return
     */
    public int updateGroupingName(Map<String, String> map) {
        Grouping grouping = groupingMapper.selectGroupingById(Long.valueOf(map.get("id")));
        if (grouping != null) {
            grouping.setName(map.get("name"));
            return groupingMapper.updateGrouping(grouping);
        } else {
            throw new XException("暂无查到该分组");
        }
    }

    /**
     * 群主修改群介绍
     *
     * @param map
     * @return
     */
    public int updateUserGroupGroupRemarks(Map<String, String> map) {
        UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.valueOf(map.get("id")));
        if (userGroup != null) {
            userGroup.setGroupRemarks(map.get("introduce"));
            return userGroupMapper.updateUserGroup(userGroup);
        } else {
            throw new XException("暂无找到该群信息,请确认在修改");
        }
    }

    /**
     * 创建群聊
     *
     * @param map
     * @return
     */
    public String createUserGroup(Map<String, String> map) {
        int count = 0;
        String gropupId = "";
        if (StringUtils.isEmpty(map.get("groupName"))) {
            throw new XException("请填写群名称");
        } else if (StringUtils.isEmpty(map.get("userId"))) {
            throw new XException("用户id不能为空");
        } else {
            String shopperId = userGroupMapper.getShopperId(map.get("userId"));
            String limit = StringUtils.isBlank(shopperId) ? "500" : map.get("limit");
            UserGroup userGroup = new UserGroup();//群聊对象
            userGroup.setType(map.get("type"));
            userGroup.setGroupName(map.get("groupName"));
            userGroup.setCost(map.get("cost"));
            userGroup.setLongitude(map.get("longitude"));
            userGroup.setLatitude(map.get("latitude"));
            userGroup.setDistance(map.get("distance"));
            userGroup.setLimit(limit);
            userGroup.setGroupLogo(map.get("groupLogo"));
            userGroup.setGroupRemarks(map.get("groupRemarks"));
            userGroup.setAddTime(DateUtils.getDate());
            userGroup.setUserId(Long.valueOf(map.get("userId")));
            userGroup.setGroupPlace(map.get("groupPlace"));
            userGroup.setGroupSetting(1);
            userGroup.setGroupNumber((long) ((Math.random() * 9 + 1) * 100000));
            count = userGroupMapper.insertUserGroup(userGroup);
            if (count > 0) {
                gropupId = userGroupMapper.findUserGroupMaxId(map.get("userId"));//查询出最大
                if (StringUtils.isNotBlank(gropupId)) {
                    GroupDetail groupDetail = new GroupDetail();
                    groupDetail.setUserId(Long.valueOf(map.get("userId")));
                    groupDetail.setGroupId(Long.valueOf(gropupId));
                    groupDetail.setAddTime(DateUtils.getDate());
                    groupDetailMapper.insertGroupDetail(groupDetail);
                    GroupNickname groupNickname = new GroupNickname();
                    groupNickname.setGroupId(Long.valueOf(gropupId));
                    groupNickname.setUserId(Long.valueOf(map.get("userId")));
                    User user = userMapper.selectUserById(Long.valueOf(map.get("userId")));
                    if (user != null) {
                        groupNickname.setNickname(user.getNickname());
                    }
                    groupNickname.setDisturb(2);
                    groupNicknameMapper.insertGroupNickname(groupNickname);

                    GroupGroupingDetails groupGroupingDetails = new GroupGroupingDetails();
                    groupGroupingDetails.setGroupId(Long.valueOf(gropupId));
                    groupGroupingDetails.setUserId(Long.valueOf(map.get("userId")));
                    groupGroupingDetails.setGroupingId(7L);
                    groupGroupingDetailsMapper.insertGroupGroupingDetails(groupGroupingDetails);
                }
            }
        }
        return gropupId;
    }

    /**
     * 添加是验证是否已经是好友
     *
     * @param map
     * @return
     */
    public boolean verificationUserFriends(Map<String, String> map) {
        if (StringUtils.isBlank(map.get("pullerUserId")) || StringUtils.isBlank(map.get("userId"))) {
            throw new XException("参数pullerUserId或者userId不能为空");
        }
        Friends friends = friendsMapper.findFriendsByfriendsUserId(map.get("userId"), map.get("pullerUserId"), "6");
        if (friends != null) {
            return true;
        }
        return false;
    }


    /**
     * 删除好友
     *
     * @param map
     * @return
     */
    public int deleteUserFriends(Map<String, String> map) {
        if (StringUtils.isBlank(map.get("pullerUserId")) || StringUtils.isBlank(map.get("userId"))) {
            throw new XException("参数pullerUserId或者userId不能为空");
        }
        Friends friends = friendsMapper.findFriendsByfriendsUserId(map.get("pullerUserId"), map.get("userId"), "6");
        Friends friends1 = friendsMapper.findFriendsByfriendsUserId(map.get("userId"), map.get("pullerUserId"), "6");
        FriendApplication friendApplication = friendApplicationMapper.findFriendApplicationByApplicantIdAndClaimantId(map.get("userId") + "", map.get("pullerUserId") + "");
        if (friendApplication != null) {
            friendApplication.setStatus(8);
            friendApplicationMapper.updateFriendApplication(friendApplication);
        }
        FriendApplication friendApplication1 = friendApplicationMapper.findFriendApplicationByApplicantIdAndClaimantId(map.get("pullerUserId") + "", map.get("userId") + "");
        if (friendApplication1 != null) {
            friendApplication1.setStatus(8);
            friendApplicationMapper.updateFriendApplication(friendApplication1);
        }
        if (friends != null && friends1 != null) {
            return friendsMapper.deleteFriendsByIds(new String[]{friends.getId() + "", friends1.getId() + ""});
        } else {
            return 0;
        }
    }

    /**
     * 群主邀请好友进群
     *
     * @param map
     * @return
     */
    public int invitations(Map<String, String> map) {
        if (StringUtils.isBlank(map.get("applicantId"))) {
            throw new XException("applicantId参数不能为空");
        }
        if (StringUtils.isBlank(map.get("groupsId"))) {
            throw new XException("groupsId参数不能为空");
        }
        if (StringUtils.isBlank(map.get("claimantId"))) {
            throw new XException("claimantId参数不能为空");
        }
        String[] claimantId = map.get("claimantId").split(",");
        if (claimantId != null && claimantId.length > 0) {
            for (String s : claimantId) {
                FriendApplication friendApplication = friendApplicationMapper.invitationsVerification(map.get("applicantId"), map.get("groupsId"), s);
                if (friendApplication != null) {
                    if (friendApplication.getStatus() == 0) {
                        User user = userMapper.selectUserById(Long.valueOf(map.get("applicantId")));
                        UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.valueOf(map.get("groupsId")));
                        if (user != null && userGroup != null) {
                            friendApplication.setValidationMessage(user.getNickname() + "邀请你加入群" + userGroup.getGroupName());//验证信息
                            friendApplication.setRemarks(user.getNickname() + "邀请你加入群" + userGroup.getGroupName());//备注
                        }
                        friendApplication.setApplicantId(Long.valueOf(map.get("applicantId")));//主动邀请用户id
                        friendApplication.setClaimantId(Long.valueOf(s));//被邀请入群用户id
                        friendApplication.setGroupsId(Long.valueOf(map.get("groupsId")));
                        friendApplication.setApplyType(3);
                        friendApplication.setStatus(0);
                        friendApplication.setAddTime((System.currentTimeMillis() / 1000) + "");
                        return friendApplicationMapper.updateFriendApplication(friendApplication);
                    } else {
                        throw new XException("您的好友已经成为了该群成员了");
                    }
                } else {
                    friendApplication = new FriendApplication();
                    User user = userMapper.selectUserById(Long.valueOf(map.get("applicantId")));
                    UserGroup userGroup = userGroupMapper.selectUserGroupById(Long.valueOf(map.get("groupsId")));
                    if (user != null && userGroup != null) {
                        friendApplication.setValidationMessage(user.getNickname() + "邀请你加入群" + userGroup.getGroupName());//验证信息
                        friendApplication.setRemarks(user.getNickname() + "邀请你加入群" + userGroup.getGroupName());//备注
                    }
                    friendApplication.setApplicantId(Long.valueOf(map.get("applicantId")));//主动邀请用户id
                    friendApplication.setClaimantId(Long.valueOf(s));//被邀请入群用户id
                    friendApplication.setGroupsId(Long.valueOf(map.get("groupsId")));
                    friendApplication.setApplyType(3);
                    friendApplication.setStatus(0);
                    friendApplication.setAddTime((System.currentTimeMillis() / 1000) + "");
                    return friendApplicationMapper.insertFriendApplication(friendApplication);
                }
            }
        }
        return 0;
    }


    /**
     * 查询群验证通知信息
     *
     * @param userId
     * @return
     */
    public List<FriendApplication> findUserGroupListByGroupUserId(String userId) {
        List<FriendApplication> list = friendApplicationMapper.findUserGroupListByUserId(userId);
        return list;
    }

    /**
     * 查询自己被其他用户邀请进群需要自己同意的验证信息
     *
     * @param userId
     * @return
     */
    public List<FriendApplication> findClaimantUserByClaimantId(String userId) {
        List<FriendApplication> list = friendApplicationMapper.findClaimantUserByClaimantId(userId);
        return list;
    }

    /**
     * 邀请用户进群确认（受邀请方确认）
     * type(0未处理1、同意、2、拒绝)
     *
     * @param map
     * @return
     */
    public int userConfirmation(Map<String, Object> map) {
        FriendApplication friendApplication = friendApplicationMapper.selectFriendApplicationById(Long.valueOf(map.get("friendId") + ""));
        if (friendApplication != null) {
            if (Integer.valueOf(map.get("type") + "") == 1) {

                GroupGroupingDetails groupGroupingDetails = new GroupGroupingDetails();//用户群分组明细表
                groupGroupingDetails.setGroupId(friendApplication.getGroupsId());//群id
                groupGroupingDetails.setGroupingId(Long.valueOf(7));//分组id
                if (friendApplication.getApplyType() == 3) {
                    groupGroupingDetails.setUserId(friendApplication.getClaimantId());
                } else {
                    groupGroupingDetails.setUserId(friendApplication.getApplicantId());
                }
                groupGroupingDetailsMapper.insertGroupGroupingDetails(groupGroupingDetails);
                GroupDetail groupDetail = new GroupDetail();//群明细表
                if (friendApplication.getApplyType() == 3) {
                    groupDetail.setUserId(friendApplication.getClaimantId());//用户id
                } else {
                    groupDetail.setUserId(friendApplication.getApplicantId());//用户id

                }
                groupDetail.setGroupId(friendApplication.getGroupsId());//群id
                groupDetail.setAddTime(DateUtils.getTime());//添加时间
                groupDetailMapper.insertGroupDetail(groupDetail);
                GroupNickname groupNickname = new GroupNickname();//群昵称表
                groupNickname.setGroupId(friendApplication.getGroupsId());//群id
                if (friendApplication.getApplyType() == 3) {
                    groupNickname.setUserId(friendApplication.getClaimantId());//用户id
                    User user = userMapper.selectUserById(friendApplication.getClaimantId());
                    if (user != null) {
                        groupNickname.setNickname(user.getNickname());
                    }
                } else {
                    groupNickname.setUserId(friendApplication.getApplicantId());//用户id
                    User user = userMapper.selectUserById(friendApplication.getApplicantId());
                    if (user != null) {
                        groupNickname.setNickname(user.getNickname());
                    }
                }
                groupNickname.setDisturb(2);
                groupNicknameMapper.insertGroupNickname(groupNickname);
                friendApplication.setStatus(Integer.valueOf(map.get("type") + ""));
                friendApplicationMapper.updateFriendApplication(friendApplication);
                return 1;
            } else {
                friendApplication.setStatus(Integer.valueOf(map.get("type") + ""));
                friendApplicationMapper.updateFriendApplication(friendApplication);
            }
        }
        return 0;
    }

    /**
     * 添加闺蜜
     */
    public int insertConfidante(String userId, String confidanteId) {
        return userGroupMapper.insertConfidante(userId, confidanteId);
    }

    /**
     * 删除闺蜜
     */
    public int deleteConfidante(String userId, String confidanteId) {
        return userGroupMapper.deleteConfidante(userId, confidanteId);
    }

    /**
     * 查询闺蜜
     */
    public List<Map<String, Object>> selectConfidante(String userId) {
        return userGroupMapper.selectConfidante(userId);
    }

    /**
     * 查询群聊里没有的闺蜜
     */
    public List<Map<String, Object>> selectNotJoinGroupConfidante(String userId, String groupId) {
        return userGroupMapper.selectNotJoinGroupConfidante(userId, groupId);
    }

    /**
     * 查询群聊里已有的闺蜜
     */
    public List<Map<String, Object>> selectJoinGroupConfidante(String userId, String groupId) {
        return userGroupMapper.selectJoinGroupConfidante(userId, groupId);
    }

    /**
     * 注册时将用户数据统一到IM组件用户表中
     *
     * @return
     */
    public int addUser(WqEweiShopMember shopMember) {
        System.out.println(shopMember);
        User user = new User();
        user.setMemberId(Integer.valueOf(shopMember.getOpenid())); //用户ID号
        String birthyear = shopMember.getBirthyear();
        String birthmonth = shopMember.getBirthmonth();
        String birthday = shopMember.getBirthday();
        user.setBirthDate(birthyear + birthmonth + birthday); //生日
        user.setPhone(shopMember.getMobile()); //电话
        user.setSex(shopMember.getGender()); //性别
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setRegistrationTime(sdf.format(new Date())); //注册时间
        user.setLogo(shopMember.getAvatar());//头像
        String province = shopMember.getProvince();
        String city = shopMember.getCity();
        String area = shopMember.getArea();
        user.setLocationAddress(province + city + area); //地址
        return userMapper.insertUser(user);
    }

    /**
     * 修改用户信息
     *
     * @param shopMember
     * @return
     */
    public int updateUsers(WqEweiShopMember shopMember) {
        User user = new User();
        user.setMemberId(Integer.valueOf(shopMember.getOpenid())); //用户ID号
        String birthyear = shopMember.getBirthyear();
        String birthmonth = shopMember.getBirthmonth();
        String birthday = shopMember.getBirthday();
        user.setBirthDate(birthyear + birthmonth + birthday); //生日
        user.setPhone(shopMember.getMobile()); //电话
        user.setSex(shopMember.getGender()); //性别
        user.setNickname(shopMember.getNickname());//昵称
        String province = shopMember.getProvince();
        String city = shopMember.getCity();
        String area = shopMember.getArea();
        user.setLocationAddress(province + city + area);//所在地
        user.setSex(shopMember.getGender());
        user.setLogo(shopMember.getAvatar());
        return userMapper.updateUsers(user);
    }

    /**
     * 删除某一条验证信息
     *
     * @param id
     * @return
     */
    public Object deleteMessageById(Long id) {
        return friendApplicationMapper.deleteFriendApplicationById(id);
    }
}
